package com.lfk.blog.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lfk.api.client.UserClient;
import com.lfk.api.dto.*;
import com.lfk.blog.mapper.BlogMapper;
import com.lfk.blog.service.IBlogService;
import com.lfk.blog.utils.JedisPoolUtil;
import com.lfk.blog.utils.RedisConstants;
import com.lfk.blog.utils.SystemConstants;
import com.lfk.blog.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.lfk.blog.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.lfk.blog.utils.RedisConstants.FEED_KEY;


/**
 * <p>
 * 博客服务实现类
 * </p>
 *
 * @author Cat凯
 * @since 2023-2-1
 */
@Service
@RequiredArgsConstructor
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {


//    private final RestTemplate restTemplate;
//
//    private final DiscoveryClient discoveryClient;
//    @Resource
//    private UserServiceImpl userService;
    private final UserClient userClient;
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Result queryBlogById(Long id) {
        //查询blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("博客不存在");
        }
        //查询blog有关的用户
        queryBlogUser(blog);
        //查询blog是否被点赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }


    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result likeBlog(Long id) {
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2.判断当前用户有无点赞
        String key = BLOG_LIKED_KEY + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        //3.如果未点赞,可以点赞
        if (score == null) {
            //3.1数据库点赞数+1
            boolean isSuccess = update().setSql("liked=liked+1").eq("id", id).update();
            //3.2保存用户到redis中的set集合
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            //4.如果已点赞,取消点赞
            //4.1数据库点赞数-1
            boolean isSuccess = update().setSql("liked=liked-1").eq("id", id).update();
            //4.2把用户从redis的set集合移除
            stringRedisTemplate.opsForZSet().remove(key, userId.toString());
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = BLOG_LIKED_KEY + id;
        //1.查询top5的点赞用户
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        //2.解析其中的用户id(转为stream流)
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        //3.根据用户id查询用户  where id in (5,1) order by field(id,5,1)
        String idStr = StrUtil.join(",", ids);
/*//        List<UserDTO> userDTOS = userService.query()
//                .in("id", id)
//                .last("order by field(id," + idStr + ")").list()
//                .stream()
//                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
//                .collect(Collectors.toList());
        //根据服务名称获取服务实例列表
        List<ServiceInstance>instances=discoveryClient.getInstances("user-service");
        if(instances.isEmpty()){
            return Result.fail("User服务不可用");
        }
        ServiceInstance instance=instances.get(RandomUtil.randomInt(instances.size()));
        ResponseEntity<List<UserDTO>> response = restTemplate.exchange(//此法无法知道服务调用者地址,服务治理 存在问题
                instance.getUri()+"/api/user/getUser?idStr={idStr},id={id}",
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<UserDTO>>() {
                },//反射拿到泛型类型
                new HashMap<String, String>() {{
                    put("idStr", idStr);
                    put("id", String.valueOf(id));
                }}
        );*/
        List<UserDTO> userDTOS = userClient.queryUserLikesByIds(idStr, ids);

        //4.返回
        return Result.ok(userDTOS);
    }

    @Override
    @Transactional
    public Result saveBlog(Blog blog) {
        //1.获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        //2.保存探店笔记
        boolean isSuccess = save(blog);//若未选择商户会报错
        //提交确认后，再存放一次到redis里另一个set集合
        JedisPool jedisPool= JedisPoolUtil.getJedisPoolInstance();
        Jedis jedis=jedisPool.getResource();
        for(String fileName:blog.getImages().split(",")){
            jedis.sadd(RedisConstants.SETMEAL_PIC_DB_RESOURCES, fileName);
        }
        jedis.close();
        if (!isSuccess) {
            return Result.fail("新增笔记失败!");
        }
        //3.查询笔记作者的所有粉丝 select * from tb_follow where follow_user_id = ?
        List<Follow> follows = userClient.queryFollowByIds(user.getId());
        //4.推送笔记id给所有粉丝
        for (Follow follow : follows) {
            //4.1获取粉丝id
            Long userId = follow.getUserId();
            //4.2推送
            String key = FEED_KEY  + userId;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        //5.返回id
        return Result.ok(blog.getId());

    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2.查询收件箱 ZREVRANGEBYSCORE key Max Min LIMIT offset count
        String key = FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        // 3.非空判断
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        // 4.解析数据：blogId、minTime（时间戳）、offset
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0; // 2
        int os = 1; // 2
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) { // 5 4 4 2 2
            // 4.1.获取id
            ids.add(Long.valueOf(tuple.getValue()));
            // 4.2.获取分数(时间戳）
            long time = tuple.getScore().longValue();
            if(time == minTime){
                os++;
            }else{
                minTime = time;
                os = 1;
            }
        }
        os = minTime == max ? os : os + offset;
        // 5.根据id查询blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();

        for (Blog blog : blogs) {
            // 5.1.查询blog有关的用户
            queryBlogUser(blog);
            // 5.2.查询blog是否被点赞
            isBlogLiked(blog);
        }

        // 6.封装并返回
        ScrollResult r = new ScrollResult();
        r.setList(blogs);
        r.setOffset(os);
        r.setMinTime(minTime);

        return Result.ok(r);
    }


    private void isBlogLiked(Blog blog) {
        UserDTO userDTO = UserHolder.getUser();
        if (userDTO == null) {
            //用户未登录,无需查询是否点赞
            return;
        }
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2.判断当前用户有无点赞
        String key = BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }


    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = (User) userClient.queryUserById(userId).getData();
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
